<template>
  <div class="w-full h-[calc(100vh-190px)] overflow-y-scroll scrollbar" ref="MessageListRef">
    <div class="w-full rounded-lg p-2" v-for="(item, index) in ai.AiMessageList" :key="index">
      <template v-if="item.type != 2">
        <div class="w-full flex flex-row-reverse items-center gap-2">
          <n-avatar :src="user.avatar" :size="30" />
          <div class="bg-[#414158] p-2 rounded-xl">
            {{ item.content }}
          </div>
        </div>
      </template>
      <template v-else>
        <div class="grid grid-cols-[30px_1fr] items-start gap-2">
          <img alt="logo" class="w-[30px] h-[30px]" src="@/assets/images/openai.svg" />
          <MdPreview :id="id" :modelValue="item.content" theme="dark" class="px-2 pb-2 rounded" />
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useUser } from "@/store/modules/user";

import "md-editor-v3/lib/preview.css";
import { NAvatar } from "naive-ui";
import { MdPreview } from "md-editor-v3";
import { nextTick, ref } from "vue";
import { UseAI } from "@/store/modules/ai";
import { useMitt } from "@/hooks/useMitt";
let MessageListRef = ref();
const id = "preview-only";
const user = useUser();
const ai = UseAI();

async function ScrollBottom(smooth = true) {
  await nextTick();
  if (!MessageListRef.value) return;
  const container = MessageListRef.value;
  if (container.scrollHeight <= 0) return;
  container.scrollTo({
    top: container.scrollHeight,
    behavior: smooth ? "smooth" : "auto",
  });
  const checkScroll = () => {
    if (container.scrollHeight > container.scrollTop + container.clientHeight) {
      container.scrollTo({
        top: container.scrollHeight,
        behavior: smooth ? "smooth" : "auto",
      });
    }
  };
  const observer = new MutationObserver(checkScroll);
  observer.observe(container, { childList: true, subtree: true });
  setTimeout(() => {
    observer.disconnect();
  }, 1000);
}

defineExpose({
  ScrollBottom,
});

useMitt.on("aiChatScrollBottom", ScrollBottom);
</script>

<style lang="scss" scoped>
:deep(#preview-only-preview) {
  font-size: 14px;
}
</style>
